package com.ccod.mapper.spring.utils;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.File;
import java.io.IOException;
import java.util.Objects;
import java.util.stream.Stream;

/**
 * 资源加载工具
 *
 * @author: ccod
 * @data: 2020/12/5 10:49
 **/
public class ResourceResolveUtils {

    /**
     * 这种方式可以借鉴mybatis的处理
     * @see org.mybatis.spring.boot.autoconfigure.MybatisProperties#resolveMapperLocations≤()
     */
    private static final ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();

    /**
     * 功能描述: <br>
     * 〈将指定classpath路径资源加载〉
     * @Param: [mapperLocations]
     * @Return: org.springframework.core.io.Resource[]
     * @Author: Ccod
     * @Date: 2020/12/5 10:54
     */
    public static File[] resolveMapperFiles(String[] mapperLocations) {
        return Stream.of(mapperLocations)
                .flatMap(location -> Stream.of(getResources(location)))
                .map(resource -> {
                    try {
                        return resource.getFile();
                    } catch (IOException e) {
                        return null;
                    }
                })
                .filter(Objects::nonNull)
                .toArray(File[]::new);
    }


    /**
     * 功能描述: <br>
     * 〈加载指定路径资源文件〉
     * @Param: [location]
     * @Return: org.springframework.core.io.Resource[]
     * @Author: Ccod
     * @Date: 2020/12/5 10:54
     */
    private static Resource[] getResources(String location) {
        try {
            return resourceResolver.getResources(location);
        } catch (IOException e) {
            return new Resource[0];
        }
    }
}
